﻿package com.sz.common.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sz.common.ICommonDAO;

public class CommonDispatcher extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected final Log logger = LogFactory.getLog(getClass());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		doPost(request, response);
		
	}
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String path = request.getContextPath();  //形如：/otprj
			String uri = request.getRequestURI();//形如：/otprj/ticket.do
			String action = uri.substring(path.length()); //形如: /ticket.do
			String sql = String.format("select * from common_dispatch where action = '%s'", action);
			
			logger.info(String.format("取映射:\n%s",sql));
		
			//ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
			ServletContext servletContext = request.getSession().getServletContext();        
			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);   

			ICommonDAO dao = (ICommonDAO)context.getBean("CommonDAO");
			Map map = (Map)dao.queryForObject(sql);
			if(map != null) {
				request.getRequestDispatcher(map.get("VIEWPAGE").toString()).forward(request, response);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e.getMessage());
		}
	}


}
